package com.pjchat.pjchatclient.handlerImpl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;

import javax.swing.JFrame;

import com.ita.im.model.ErrorMessageType;
import com.ita.im.model.Unit;
import com.ita.im.model.User;
import com.pjchat.pjchatclient.frame.MyClientFrame;
import com.pjchat.pjchatclient.frame.MyLoginFrame;
import com.pjchat.pjchatclient.handler.BasicHandler;
import com.pjchat.pjchatclient.sender.ForwardSender;
import com.pjchat.pjchatclient.util.ErrorMessageUtil;

public class HandlerForLogin extends BasicHandler {
	private static HandlerForLogin instance;

	private HandlerForLogin() {

	}

	public static HandlerForLogin getInstance() {
		if (instance == null) {
			instance = new HandlerForLogin();
		}
		return instance;
	}

	@Override
	public Unit doRequest(JFrame frame, Unit unit, BufferedReader br,
			BufferedWriter bw) {
		ForwardSender.send(bw, unit);
		return null;
	}

	@Override
	public Unit doResponse(JFrame frame, Unit unit, BufferedReader br,
			BufferedWriter bw) {
		MyLoginFrame myFrame = (MyLoginFrame) frame;
		if (unit.isSuccess()) {
			try {
				MyClientFrame mcf = new MyClientFrame(br, bw, (User) unit
						.getValue().get("user"));
			} catch (IOException e) {
				e.printStackTrace();
			}
			myFrame.switchFrame();
			return unit;
		} else {
			myFrame.getMyResult().setText(
					ErrorMessageUtil.getErrorMessage((ErrorMessageType) unit
							.getValue().get("error_message")));
		}
		return null;
	}

}
